<?php

/*
=====================================================
ExpressionEngine - by pMachine
-----------------------------------------------------
http://www.pmachine.com/
-----------------------------------------------------
Copyright (c) 2003 - 2004 pMachine, Inc.
=====================================================
THIS IS COPYRIGHTED SOFTWARE
PLEASE READ THE LICENSE AGREEMENT
http://www.pmachine.com/expressionengine/license.html
=====================================================
File: mcp.ncaggregator.php
-----------------------------------------------------
Purpose: rss aggregatior - CP
=====================================================
*/

class Ncaggregator_CP {

    var $version        = '1.0 rc3';
    
    // -------------------------
    //  Constructor
    // -------------------------
    
    function Ncaggregator_CP( $switch = TRUE )
    {
        global $IN;
        
        if ($switch)
        {
            switch($IN->GBL('P'))
            {
                 case 'view'            :    $this->view_feeds();
                     break;    
                 case 'delete_con'      :    $this->delete_feed_confirm();
                     break;
                 case 'delete'          :    $this->delete_feed();
                     break;    
                 case 'save'            :    $this->save_feed();
                     break;
                 case 'add'             :    $this->add_feed();
                     break;
                 case 'modify'          :    $this->add_feed();
                     break;
                 default                :    $this->feeds_home();
                     break; 
            }
        }
    }// END
    
    
    
    
    
    // ----------------------------------------
    //  Module Homepage
    // ----------------------------------------

    function feeds_home($msg='')
    {
      global $DSP, $LANG, $DB, $FNS;
      $r='';
        
        // -------------------------------------------------------
        //  Select All Feeds from Database
        // -------------------------------------------------------
        
        $query = $DB->query("SELECT * FROM exp_feeds ORDER BY feed_order");
                                
        if ($query->num_rows == 0){
            $msg="No feeds entered!";        
        }

        // -------------------------------------------------------
        //  HTML Title and Navigation Crumblinks
        // -------------------------------------------------------
        
        $DSP->title = $LANG->line('feeds_module_name');
        $DSP->crumb = $DSP->anchor(BASE.
                                   AMP.'C=modules'.
                                   AMP.'M=ncaggregator',
                                   $LANG->line('feeds_module_name'));
        // -------------------------------------------------------
        //  Page Heading and Success Message, if any
        // -------------------------------------------------------
        

                                       
        $DSP->crumb .= $DSP->crumb_item($LANG->line('feeds_menu'));    
        
        // -------------------------------------------------------
        //  Table and Table Headers
        // -------------------------------------------------------
        
        			
        $DSP->right_crumb($LANG->line('add_feed'), BASE.AMP.'C=modules'.AMP.'M=ncaggregator'.AMP.'P=add');
        
        $DSP->body .= $DSP->qdiv('tableHeading', $LANG->line('active_rss')); 
        
        $DSP->body .= $DSP->table('tableBorder', '0', '10', '100%').
					  $DSP->tr().
					  $DSP->td('tableHeadingAlt', '', '').$LANG->line('feed_id').$DSP->td_c().
					  $DSP->td('tableHeadingAlt', '', '').$LANG->line('feed_name').$DSP->td_c().
					  $DSP->td('tableHeadingAlt', '', '').$LANG->line('edit').$DSP->td_c().
					  $DSP->td('tableHeadingAlt', '', '').$LANG->line('delete').$DSP->td_c().
					  $DSP->tr_c();
        
        if ($msg != '')
        {
			     $DSP->body .= $DSP->qdiv('successBox', $DSP->qdiv('success', $msg));
        }    

        $i = 0;
        
        // -------------------------------------------------------
        //  Display Rows of Fortunes
        // -------------------------------------------------------
        
        foreach($query->result as $row)
        {
            $style = ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo';
                      
            $r .= $DSP->tr();

            $r .= $DSP->table_qcell($style, $row['feed_id'],'5%','top');

            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE.
                                                          AMP.'C=modules'.
                                                          AMP.'M=ncaggregator'.
                                                          AMP.'P=modify'.
                                                          AMP.'feed_id='.
                                                          $row['feed_id'],
                                                          '<b>'.$row['feed_name'].'</b>'),
                                                          '70%','top');
            
            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE.
                                                          AMP.'C=modules'.
                                                          AMP.'M=ncaggregator'.
                                                          AMP.'P=modify'.
                                                          AMP.'feed_id='.
                                                          $row['feed_id'],
                                                          $LANG->line('edit')),'15%','top');
                                                          
            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE.
                                                          AMP.'C=modules'.
                                                          AMP.'M=ncaggregator'.
                                                          AMP.'P=delete_con'.
                                                          AMP.'feed_id='.
                                                          $row['feed_id'],
                                                          $LANG->line('delete')),'15%','top');
                                                          
            $r .= $DSP->tr_c();
            
        }
        
        // -------------------------------------------------------
        //  Close Table and Output to $DSP->body
        // -------------------------------------------------------

        $r .= $DSP->table_c();

        $r .= $DSP->td_c()   
             .$DSP->tr_c()      
             .$DSP->table_c();
        
        $DSP->body .= $r;


    }
    // END
    
    
    
    
    // -------------------------------------------
    //   Delete Feed Confirmation
    // -------------------------------------------    

    function delete_feed_confirm()
    { 
        global $IN, $DSP, $LANG, $DB;
        
         		if (is_numeric($IN->GBL('feed_id')))
          {
          	$query = $DB->query("SELECT * FROM exp_feeds WHERE feed_id = '".$DB->escape_str($IN->GBL('feed_id'))."'");
          	
          	if ($query->num_rows == 1)
          	{
          		$feed_id = $query->row['feed_id'];
          		$feed_name = $query->row['feed_name'];
          	}
        }
        
        $DSP->title = $LANG->line('feeds_module_name');
    		$DSP->crumb  = $DSP->anchor(BASE.AMP.'C=modules'.AMP.'M=ncaggregator', $LANG->line('feeds_module_name'));
    		$DSP->crumb .= $DSP->crumb_item($LANG->line('feeds_delete'));
        $DSP->body	.=	$DSP->form_open(array('action' => 'C=modules'.AMP.'M=ncaggregator'.AMP.'P=delete'.AMP.'feed_id='.$feed_id.'',));
    

    		
    		$query = $DB->query($sql);        
            
    		$DSP->body .= $DSP->qdiv('alertHeading', $LANG->line('delete_feed_title'));
    		$DSP->body .= $DSP->div('box');
    		$DSP->body .= $DSP->qdiv('defaultBold', $DSP->qdiv('itemWrapper', $LANG->line('delete_question')));
    		
    		$DSP->body .= $DSP->qdiv('itemWrapper', $DSP->qdiv('highlight', NBS.NBS.NBS.NBS.$feed_name));
    		
    		$DSP->body .= $DSP->qdiv('alert', BR.$LANG->line('delete_warning1'));		
    		$DSP->body .= $DSP->qdiv('alert', BR.$LANG->line('delete_warning2'));
    		$DSP->body .= $DSP->qdiv('', BR.$DSP->input_submit($LANG->line('delete')));
    		$DSP->body .= $DSP->qdiv('alert',$DSP->div_c());
    		$DSP->body .= $DSP->div_c();
    		$DSP->body .= $DSP->form_close();
    }
    // END   
    
    
    
    

    // -------------------------
    // Delete Feed
    // -------------------------
    
    function delete_feed()
    {
        global $LANG, $DB, $IN, $DSP;
        
           
        // -------------------------------------------------------
        //  Feed ID is required
        // -------------------------------------------------------
        
        if ( ! is_numeric($IN->GBL('feed_id')))
        {
            $DSP->body .= $DSP->error_message($LANG->line('invalid_feed_id').$IN->GBL('feed_id'));        
            return;
        }
        else
        {
            $query = $DB->query("DELETE FROM exp_feeds
                                 WHERE feed_id = '".$IN->GBL('feed_id')."'");
                                
            if ($DB->affected_rows == 0)
            {
                $DSP->body .= $DSP->error_message($LANG->line('invalid_feed_id'));        
                return;
            }
        }
        
        // -------------------------------------------------------
        //  Return to View Feeds with Success Message
        // -------------------------------------------------------
        
        return $this->feeds_home($LANG->line('feed_deleted'));        
    }
    // END 






    // -------------------------
    //  Add/Edit Feed
    // -------------------------
    function add_feed()
    {
  		global $IN, $DSP, $LANG, $DB;
  		        
          $feed_id	= '0';
          $feed_url	= '';
          $feed_name	= '';
          $feed_order='';
          
          if (is_numeric($IN->GBL('feed_id')))
          {
          	$query = $DB->query("SELECT * FROM exp_feeds WHERE feed_id = '".$DB->escape_str($IN->GBL('feed_id'))."'");
          	
          	if ($query->num_rows == 1)
          	{
          		$feed_id = $query->row['feed_id'];
          		$feed_name = $query->row['feed_name'];
              $feed_url = $query->row['feed_url'];
              $feed_order = $query->row['feed_order'];
          	}
          }
          
      $title = ($feed_id == 0) ? $LANG->line('add_feed') : $LANG->line('edit_feed');
      $DSP->title = $title;        
  		$DSP->crumb  = $DSP->anchor(BASE.AMP.'C=modules'.AMP.'M=ncaggregator', $LANG->line('feeds_module_name'));
  		$DSP->crumb .= $DSP->crumb_item($title);
  
      $DSP->body .= $DSP->qdiv('tableHeading', $title); 
                          
      $DSP->body	.=	$DSP->form_open(
          						  array('action' => 'C=modules'.AMP.'M=ncaggregator'.AMP.'P=save'),
          						  array('feed_id' => $feed_id)
          						);
  
      $DSP->body	.=	$DSP->table('tableBorder', '0', '0', '100%');
  		$style ='tableCellOne';
        $DSP->body .= $DSP->tr();
    		$DSP->body .= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $DSP->required().$LANG->line('rss_name')).$DSP->qdiv('default', $LANG->line('rss_name_full')), '30%');				
    		$DSP->body .= $DSP->table_qcell($style, $DSP->qdiv('', $DSP->qdiv('itemWrapper', $DSP->input_text('feed_name', $feed_name, '35', '40', 'input', '100%'))));
    		$DSP->body .= $DSP->tr_c();
          	  
    		$DSP->body .= $DSP->tr();
    		$DSP->body .= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $DSP->required().$LANG->line('rss_url')).$DSP->qdiv('default', $LANG->line('rss_url_full')), '30%');				
    		$DSP->body .= $DSP->table_qcell($style, $DSP->qdiv('', $DSP->qdiv('itemWrapper', $DSP->input_text('feed_url', $feed_url, '35', '100', 'input', '100%'))));
    		$DSP->body .= $DSP->tr_c();
    		
    		$DSP->body .= $DSP->tr();
    		$DSP->body .= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $LANG->line('rss_order')).$DSP->qdiv('default', $LANG->line('rss_order_full')),'30%');
    		$DSP->body .= $DSP->table_qcell($style, $DSP->qdiv('', $DSP->qdiv('itemWrapper', $DSP->input_text('feed_order', $feed_order, '30', '3', 'input', '30px'))));
    		$DSP->body .= $DSP->tr_c();
      $DSP->body .= $DSP->table_c();
      $DSP->body .= $DSP->qdiv('', $DSP->required().$LANG->line('required'));
      	
      $button = ($feed_id == 0) ? $LANG->line('submit_add') : $LANG->line('submit_change');
      	
  		$DSP->body	.=	$DSP->qdiv('itemWrapperTop', $DSP->input_submit($button));             
      $DSP->body	.=	$DSP->form_close();     
    }
    // END


    // -------------------------
    //  Save Feeds
    // -------------------------

    function save_feed()
    {
  		global $IN, $DSP, $LANG, $DB;
  		
  		
  		$feed_id = (is_numeric($IN->GBL('feed_id')) && $IN->GBL('feed_id') != 0) ? $IN->GBL('feed_id') : FALSE;
          
      if ($_POST['feed_name'] == '' || $_POST['feed_url'] == ''){
          return $DSP->error_message($LANG->line('error_form'));
      }
      
      if (preg_match("/\D+/i", $_POST['feed_order'])){
          return $DSP->error_message($LANG->line('error_form'));
      }
      
    	$sql = "SELECT COUNT(*) AS count FROM exp_feeds WHERE feed_name = '".$DB->escape_str($_POST['feed_name'])."'";
  
      if ($feed_id !== FALSE){
      		$sql .= " AND feed_id != '".$feed_id."'";
      }
  
  		$query = $DB->query($sql);
  
      if ($query->row['count'] > 0){
          return $DSP->error_message($LANG->line('error_form'));
      }
      	
      if ($feed_id === FALSE){
      		$DB->query("INSERT INTO exp_feeds(feed_id, feed_name, feed_url, feed_order) values ('', '".$DB->escape_str($_POST['feed_name'])."', '".$DB->escape_str($_POST['feed_url'])."', '".$DB->escape_str($_POST['feed_order'])."')");
      }else{
      		$DB->query("UPDATE exp_feeds SET feed_name = '".$DB->escape_str($_POST['feed_name'])."', feed_url = '".$DB->escape_str($_POST['feed_url'])."', feed_order = '".$DB->escape_str($_POST['feed_order'])."' WHERE feed_id = '{$feed_id}'");
      }
      	
      $msg = ($feed_id === FALSE) ? $LANG->line('feed_created') : $LANG->line('feed_updated');
      	
      return $this->feeds_home($msg);
  
  

    }
    // END



    // ----------------------------------------
    //  Module installer
    // ----------------------------------------

    function ncaggregator_module_install()
    {
        global $DB;        
        
        $sql[] = "INSERT INTO exp_modules (module_id, module_name, module_version, has_cp_backend) 
                                           VALUES 
                                           ('', 'Ncaggregator', '$this->version', 'y')";
                                           
        $sql[] = "CREATE TABLE IF NOT EXISTS `exp_feeds` (
                 `feed_id` INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
                 `feed_name` VARCHAR(40) NOT NULL ,
                 `feed_url` VARCHAR(100) NOT NULL ,
                 `feed_order` INT(2) NOT NULL ,
                 PRIMARY KEY (`feed_id`));";
    
        foreach ($sql as $query)
        {
            $DB->query($query);
        }
        
        return true;
    }
   // ----------------------------------------
    //  Module de-installer
    // ----------------------------------------

    function ncaggregator_module_deinstall()
    {
        global $DB;    

        $query = $DB->query("SELECT module_id
                             FROM exp_modules 
                             WHERE module_name = 'Ncaggregator'"); 
                
        $sql[] = "DELETE FROM exp_module_member_groups 
                  WHERE module_id = '".$query->row['module_id']."'";      
                  
        $sql[] = "DELETE FROM exp_modules 
                  WHERE module_name = 'Ncaggregator'";
                  
        $sql[] = "DELETE FROM exp_actions 
                  WHERE class = 'Ncaggregator'";
                  
        $sql[] = "DELETE FROM exp_actions 
                  WHERE class = 'Ncaggregator_CP'";
                  
        $sql[] = "DROP TABLE IF EXISTS exp_feeds";

        foreach ($sql as $query)
        {
            $DB->query($query);
        }

        return true;
    }
    // END



}
// END CLASS
?> 
